package server.connector;

import org.apache.catalina.Request;
import org.apache.catalina.util.StringManager;
import server.connector.http.Constants;

import javax.servlet.ServletInputStream;
import java.io.IOException;
import java.io.InputStream;

//强制读取的字节数不超过给定的length,如果数据没用读完就调用close方法，close方法会读够length
//如果length<=0，读的长度没有限制
public class RequestStream extends ServletInputStream {
    protected InputStream stream = null;
    protected boolean closed = false;
    protected int count = 0;
    protected int length = -1;
    protected static StringManager sm =
            StringManager.getManager(Constants.PACKAGE);
    public RequestStream(Request request) {
        super();
        closed = false;
        count = 0;
        length = request.getRequest().getContentLength();
        stream = request.getStream();
    }
    @Override
    public int read(byte b[], int off, int len) throws IOException {
        int toRead = len;
        if (length > 0) {
            if (count >= length)
                return (-1);
            if ((count + len) > length)
                toRead = length - count;
        }
        int actuallyRead = super.read(b, off, toRead);
        return (actuallyRead);

    }
    @Override
    public int read(byte b[]) throws IOException {

        return (read(b, 0, b.length));

    }
    @Override
    public int read() throws IOException {
        if (closed)
            throw new IOException(sm.getString("requestStream.read.closed"));
        if (length >= 0 && count >= length)
            return -1;
        int b = stream.read();
        if (b >= 0)
            count++;
        return b;
    }
    @Override
    public void close() throws IOException {
        if (closed)
            throw new IOException(sm.getString("requestStream.close.closed"));
        if (length > 0) {
            while (count < length) {
                int b = read();
                if (b < 0)
                    break;
            }
        }
        closed = true;
    }
}
